package edu.ccut.saturn.workflow.parse;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnComponentException;
import edu.ccut.saturn.workflow.common.Dom4jUtils;

public class ParseFormDataValue extends DefaultComponent {
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		debug("start ParseFormDataValueXml",parameterContext);
		byte[] xml = (byte[])parameterContext.getParameterValue(0);

		HashMap<String,String> formDataValue = parseXml(xml);
		debug("end ParseFormDataValueXml",parameterContext);
		parameterContext.setParameter(1, formDataValue);
	}

	@SuppressWarnings("unchecked")
	private HashMap<String, String> parseXml(byte[] xml) throws SaturnComponentException{
		HashMap<String ,String > formDataValue = new HashMap<String, String>();
		if(xml != null){
//			debug("xml.length:"+xml.length);
//			String strs = new String(xml);
//			debug("content:"+strs);
			InputStream in = null;
			try {
				//从数据库中解析需要转码
				xml = new String(xml, "UTF-8").getBytes("UTF-8");
				in = new ByteArrayInputStream(xml);
				Document document = Dom4jUtils.getDocment(in);
				Element root = document.getRootElement();
				Element dataElement = root.element("data");
				if(dataElement!=null){
					List<Element> list = dataElement.elements();
					if(list!=null||!list.isEmpty()){
						for(Element data:list){
							formDataValue.put(data.getName(), data.getText());
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return formDataValue;
	}


}